package com.example.sonone.controller;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2020/4/24 3:02
 * @description: TODO
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 */

import com.example.sonone.util.VerifyCodeImgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("code")
@Slf4j
public class TestCodeController {

    /**
     *  测试生成图片码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
    @ResponseBody
    public String getVerifyCode(HttpServletRequest request,
                                      HttpServletResponse response) {
        try {
            VerifyCodeImgUtil.VerifyCodeInfo imageInfo = VerifyCodeImgUtil.createVerifyCode();

            log.info("验证码答案:{}", imageInfo.getResult());

            //todo 验证码答案写入到redis
   /*         redisOpsUtil.set(RedisKeyPrefixConst.MIAOSHA_VERIFY_CODE_PREFIX + memberId + ":" + productId
                    , imageInfo.getResult()
                    , 300
                    , TimeUnit.SECONDS);*/

            response.setHeader("Content-Type", "image/jpeg");
            OutputStream out = response.getOutputStream();
            ImageIO.write(imageInfo.getBufferedImage(), "JPEG", out);
            out.flush();
            out.close();
            return null;
            /**
             * 返回图片的base64编码,js解码成图片
             */
            /*ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write(imageInfo.getBufferedImage(), "png", baos);//写入流中
            byte[] bytes = baos.toByteArray();//转换成字节
            BASE64Encoder encoder = new BASE64Encoder();
            String png_base64 =  encoder.encodeBuffer(bytes).trim();//转换成base64串
            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
            return CommonResult.success(png_base64);*/
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
